<template>
    <div class="donation-records">
        <van-nav-bar title="个人主页" left-text="返回" left-arrow @click-left="goBack" />
        <van-form @submit="onSubmit" class="donation-records-form">
            <van-cell-group inset>
                <van-field label="头像">
                    <template #input>
                        <van-uploader :max-count="1" :after-read="afterRead">
                            <img :src="imageUrl + selfInfo.donatorAvatar" width="100px" />
                        </van-uploader>
                    </template>
                </van-field>
                <van-field v-model="selfInfo.donatorId" label="用户ID" readonly />
                <van-field v-model="selfInfo.donatorPhone" label="手机号" readonly />
                <van-field v-model="selfInfo.donatorUsername" label="用户名" placeholder="请输入用户名" />
                <van-field v-model="selfInfo.donatorPassword" label="密码" placeholder="请输入密码" type="password" />
            </van-cell-group>
            <div class="donation-records-btn">
                <van-button round block type="primary" native-type="submit">提交</van-button>
            </div>
        </van-form>
    </div>
</template>

<script lang="ts" setup>
import { showFailToast, showSuccessToast } from 'vant';
import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { imageUrl } from '../../api/request'
import { adminApi, donatorApi } from '../../api/app';

const router = useRouter();
/** 个人信息表单 */
const selfInfo = ref({
    donatorId: undefined,
    donatorPhone: undefined,
    donatorPassword: undefined,
    donatorUsername: undefined,
    donatorAvatar: undefined
})

onMounted(() => {
    // 获取个人信息
    const info = JSON.parse(localStorage.getItem('donator') || '');
    selfInfo.value = {
        donatorId: info.donatorId,
        donatorPhone: info.donatorPhone,
        donatorPassword: info.donatorPassword,
        donatorUsername: info.donatorUsername,
        donatorAvatar: info.donatorAvatar
    }
})

/** 返回个人主页 */
const goBack = () => {
    router.back();
}

/** 提交表单 */
const onSubmit = () => {
    adminApi.updateDonator(selfInfo.value).then((res) => {
        if (res) {
            showSuccessToast('修改成功');
            localStorage.removeItem('donator');
            localStorage.setItem('donator', JSON.stringify(selfInfo.value));
        } else {
            showFailToast('修改失败');
        }
    });
}

/** 上传头像 */
const afterRead = (file) => {
    // 用FormData转换为二进制
    const forms = new FormData();
    forms.append('file', file.file || '');
    donatorApi.uploadAvatar(forms).then((res: any) => {
        selfInfo.value.donatorAvatar = res;
    })
}
</script>

<style scoped lang="less">
.donation-records {
    width: 100vw;
    height: 100vh;
    background-color: rgba(237, 231, 231, 0.422);

    .donation-records-form {
        margin-top: 2rem;

        .donation-records-btn {
            margin-top: 2rem;
        }
    }
}
</style>